package cn.kgc.springmvc.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author: mosin
 * @version: v1.0  2022/5/6
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping("upload")
    public String uploadFile(HttpServletRequest request, MultipartFile file, Model model){
        //获取项目部署的真实路径
        String realPath = request.getSession().getServletContext().getRealPath("/upload");
        System.out.println("realPath = " + realPath);
        File f = new File(realPath);
        if(!f.exists()){
            f.mkdir();
        }
        //文件上传
        if(!file.isEmpty()){
            //获取上传文件的真实名字
            String originalFilename = file.getOriginalFilename();
            String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String fileUploadName = uuid.concat("."+filenameExtension);
            File f1 = new File(realPath, fileUploadName);
            try {
                file.transferTo(f1);
                model.addAttribute("msg", "文件上传成功!");
            } catch (IOException e) {
                e.printStackTrace();
                model.addAttribute("msg", "文件上传失败!");
            }
        }else{
            model.addAttribute("msg", "未选择文件");
        }
        model.addAttribute("msg", "文件上传成功");
        return "success";
    }



}
